/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, ListView, Dimensions, TouchableOpacity, PixelRatio, TouchableHighlight, Image, Platform, BackHandler, ScrollView, DeviceEventEmitter} from 'react-native';

import AutoHeightWebView from 'react-native-autoheight-webview';

import LinearGradient from 'react-native-linear-gradient';

import {CachedImageBackground} from "react-native-img-cache";

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import Loading from '../../component/loading';

import LoadError from '../../component/loadError';

import Share from '../../component/share';

import ColumnDetails from './columnDetails';

import Subscribe from './subscribe';

import Login from '../me/login';

const totalWidth = Dimensions.get('window').width;

const os = Platform.OS;

export default class BriefIntroduction extends Component {
  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      specialColumnList: ds,
      loading: true,
      success: false,
      errorMessage: '',
      isCollection: false,
      isBuy: false,
      webViewHeight: 0,
      sameLevel:this.props.sameLevel,
      checkDevice: '',
    };
    this.entity = {};
  }
  componentWillMount(){
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if (os === 'android') {
       BackHandler.addEventListener('hardwareBackPress', () => Common.onBack(this,{"id":this.props.did,"type":8,"collectionStatus": this.collection == this.state.isCollection}));
    }
    this.briefIntroduction = DeviceEventEmitter.addListener('successPay',()=>{
      this.setState({isBuy: true});
    });
    this.loginStatus = DeviceEventEmitter.addListener('loginStatus',()=>{
      this.fetchSpecialColumnData();
    });
    this.rememberStyle = DeviceEventEmitter.addListener('styleState',(data)=>{
      if(data && data.status && this.state.sameLevel!="" && this.location && data.id!=this.props.did){
      	this.location.scrollTo({x: 0, y:data.status, animated: false})
      }
    });
  }
  componentDidMount(){
    this.fetchSpecialColumnData();
  }
  componentWillUnmount() {
    if (os === 'android') {
       BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this,{"id":this.props.did,"type":8,"collectionStatus":this.collection == this.state.isCollection}));
    }
    this.briefIntroduction.remove();
    this.loginStatus.remove();
    this.rememberStyle.remove();
  }
  fetchSpecialColumnData = () => {
    this.setState({
      loading: true,
      success: false,
    });
    let formData = new FormData();
    formData.append("id", this.props.did);
    if(typeof loginInfo != 'undefined' && loginInfo){
      formData.append('userToken',loginInfo.userToken);
    }
    Common.fetchData("post", "/specialColumn/getHead", formData, (responseData) => {
      this.entity = responseData.entity;
      this.setState({specialColumnList: this.state.specialColumnList.cloneWithRows(responseData.entity.specialColumnList),
                      loading: false,
                      success: true,
                      isBuy: responseData.entity.isBuy,
                    });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "请求失败",
                      });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "网络错误",
                      });
    });
    Common.isCollection({id:this.props.did, type: 8}, () => {
      this.setState({isCollection: true});
      this.collection = true;
    }, () => {
      this.setState({isCollection: false});
      this.collection = false;
    });
  };
  orderBuy = () =>{
    if(typeof loginInfo != 'undefined' && loginInfo){
      Common.onForward(this, Subscribe, 8, this.props.did);
    }else{
      Common.onForward(this, Login);
    }
  };
  renderHeader = () => {
    var specialColumnNewsContentText = this.entity.specialColumnNewsContentText||"";
    return(
      <View style={styles.specialColumn}>
        {
          this.entity.specialColumnPic2?
          <CachedImageBackground style={styles.bigImg} source={{uri: this.entity.specialColumnPic2}} >
          {this.entity.isNew?
            <Image style={styles.bigImgIcon} source={require('../../images/specialColumn/NEWD.png')}/>:null
          }
        </CachedImageBackground>:null
        }
        <View style={styles.specialColumnInfo}>
          <View style={{flex: 1}}>
            <Text style={styles.specialColumnInfoTitle}>{this.entity.specialColumnTitle}</Text>
            <Text style={styles.specialColumnInfoUpdate}>更新到第{this.entity.columnNumber}期／共{this.entity.totalColumnNumber}期 {this.entity.updatePeriodInfo} <Text style={styles.specialColumnInfoMoney}>{this.entity.totalColumnMoney}元</Text></Text>
            <View style={styles.userInfo}>
              {this.entity.userPic?
                <CachedImageBackground style={styles.userImg} source={{uri: this.entity.userPic}}/>:
                <Image style={styles.userImg} source={require('../../images/me/User.png')}/>
              }
              <View style={styles.userLabel}>
                <Text style={styles.userName}>{this.entity.userName} {this.entity.userRank}</Text>
                <Text style={styles.userIntroduce}>{this.entity.userIntroself}</Text>
              </View>
            </View>
          </View>
          <Text style={styles.specialColumnLabel}>简介</Text>
        </View>
        <AutoHeightWebView
           style={[styles.specialColumnContent]}
           source={{html: "<div>"+specialColumnNewsContentText+"<br></div>"}}
        />
        {
          this.entity.specialColumnList.length?
          <Text style={styles.listUpdate}>更新到第{this.entity.columnNumber}期</Text>:null
        } 
        
      </View>
    )
  };
  renderRow = (rowData,rowId) => {
    if(rowData.lastUpdateTime){
      var date = rowData.lastUpdateTime.split(' ')[0].split('-');
    }
    return(
      <TouchableHighlight style={[styles.specialColumnItemTouch]} underlayColor="#fafafa" delayPressIn={100} onPress={() => Common.onForward(this, ColumnDetails, rowData.specialColumnTitle, rowData.id,"","no","Normal","true",this.endLocation)}>
        <View style={styles.specialColumnItem} >
          <View style={styles.specialColumnItemLeft}>
            <View style={styles.specialColumnItemPS}>
              <Text>
              <Text style={styles.specialColumnPeriod}>{rowData.columnNumber}  </Text>
              {
                rowData.isFree?<Text style={[styles.specialColumnSign,{color: '#38ba00'}]}>试读</Text>:rowData.isNew?<Text style={[styles.specialColumnSign,{color: '#fe4445'}]}>最新</Text>:null
              }
              </Text>
            </View>
            <View style={styles.specialColumnCon}>
              <Text style={styles.specialColumnConTitle} numberOfLines={2}>{rowData.specialColumnTitle}</Text>
              <Text style={styles.specialColumnConInfo} numberOfLines={2}>{rowData.specialColumnSubject}</Text>
            </View>
          </View>
          <View style={styles.specialColumnItemRight}>
            <Text style={styles.specialColumnItemRightTime}>{date?(date[1]+"月"+date[2]+"日"):null}</Text>
            {rowData.specialColumnPic1?
              <CachedImageBackground style={styles.coverImg} source={{uri: rowData.specialColumnPic1}} />:
              <View style={[styles.coverImg,{borderColor: '#ededed',borderWidth:1/PixelRatio.get()}]}>
                <Text style={{color: '#ededed',fontSize: 10}}>暂无图片</Text>
              </View>
            }
          </View>
        </View>
      </TouchableHighlight>
    )
  };
  renderScrollComponent = (props) => {
    return (
    	<ScrollView 
    		ref={(e) => this.location = e} 
            onScroll ={(event)=>{
                this.endLocation = event.nativeEvent.contentOffset.y;
            }}>
    	</ScrollView>
    );
  };
  renderFooter = () => {
    return (<View style={{width: totalWidth,height: totalWidth*0.04,backgroundColor: '#f4f4f4'}}/>)
  }
  render() {
    var marginBottom = this.state.isBuy ?0:this.state.checkDevice == 'x'?totalWidth*0.189:totalWidth*0.139;
    var collectionIcon = this.state.isCollection?require("../../images/collection/Collectionon.png"):require("../../images/collection/Collectionoff.png");
    return (
      <View style={styles.container} >
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this,{"id":this.props.did,"type":8,"collectionStatus": this.collection == this.state.isCollection});
            },
          }}
          extraItem={{
            title: 'Collection',
            layout: 'icon',
            icon: collectionIcon,
            onPress: () => {
              if(this.state.isCollection){
                Common.deleteCollection({id: this.props.did, type: 8},() => {
                  this.setState({isCollection: false});
                });
              }else{
                Common.addCollection({id: this.props.did, type: 8},() => {
                  this.setState({isCollection: true});
                });
              }
            },
          }}
          rightItem={{
            title: 'Share',
            layout: 'icon',
            icon: require("../../images/share/share.png"),
            onPress: () => {
              if(this.refs.share){
                this.refs.share.show(this.locations, this.entity.id,false);
              }
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>专栏详情</Text>
          </View>
        </ToolbarComponent>
        {
        this.state.loading?
          <Loading />:
          (this.state.success?
            <View style={{flex: 1}} >
              <ScrollView>
                <View ref={(e) => this.locations = e} style={{marginBottom: marginBottom,backgroundColor:'#f4f4f4'}}>
                  <ListView
                    dataSource={this.state.specialColumnList}
                    renderHeader={this.renderHeader}
                    renderFooter={this.renderFooter}
                    renderRow={this.renderRow}
                    stickySectionHeadersEnabled={true}
                    enableEmptySections={true}
                    directionalLockEnabled={true}
                    renderScrollComponent={this.renderScrollComponent}
                  />
                </View>
              </ScrollView>
              {
                this.state.isBuy ? null:
                <View style={[styles.bottom]}>
                  <LinearGradient colors={['rgba(0,0,0, 0)', 'rgba(19,19,19,0.03)']} style={{width: totalWidth,height: totalWidth*0.015}} />
                  <View style={[styles.bottomCon,this.state.checkDevice == 'x'?{paddingBottom: totalWidth*0.08}:null]}>
                    <View style={styles.bottomLeft}>
                      <Text style={styles.bottomLeftT}>订阅获取更多精彩内容</Text>
                      <Text style={styles.bottomLeftM}>{this.entity.totalColumnMoney}元</Text>
                    </View>
                    <TouchableOpacity style={styles.bottomRight} onPress={this.orderBuy}>
                      <Text style={styles.bottomRightT}>订阅</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              }
            </View>:<LoadError reload={this.fetchSpecialColumnData} reason={this.state.errorMessage}/>
            )
          }
        <Share ref="share" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f4f4f4'
  },
  toolbarV: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  toolbarT: {
    color: '#ffffff',  
    fontWeight: 'bold',
    fontSize: 20
  },
  specialColumn: {
    flex: 1,
    backgroundColor: '#fff',
  },
  bigImg: {
    width: totalWidth,
    height: totalWidth*0.644,
    alignItems: 'flex-end',
  },
  bigImgIcon: {
    marginRight: 10,
  },
  specialColumnInfo: {
    flex: 1,
    paddingHorizontal: totalWidth*0.06,
  },
  specialColumnContent: {
    paddingHorizontal: totalWidth*0.05,
  },
  specialColumnInfoTitle: {
    paddingTop: totalWidth*0.045,
    fontSize: 20,
    color: '#000',
  },
  specialColumnInfoUpdate: {
    fontSize: 10,
    color: '#939393',
    marginTop: 10,
  },
  specialColumnInfoMoney: {
    color: '#f9be36',
  },
  userInfo: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    paddingVertical: totalWidth*0.042,
    borderColor: '#dbdbdb',
    borderBottomWidth: 2/PixelRatio.get(),
  },
  userImg: {
    width: totalWidth*0.138,
    height: totalWidth*0.138,
    borderRadius: totalWidth*0.069,
    marginRight: 7,
  },
  userLabel: {
    flex: 1,
  },
  userName: {
    color: '#000',
    fontSize: 15,
  },
  userIntroduce: {
    color: '#939393',
    fontSize: 10,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialColumnLabel: {
    color: '#b2b2b2',
    fontSize: 10,
    marginTop: totalWidth*0.056,
    marginBottom: totalWidth*0.024,
  },
  listUpdate: {
    paddingHorizontal: totalWidth*0.07,
    paddingVertical: 3,
    color: '#787878',
    fontSize: 10,
    backgroundColor: '#f4f4f4'
  },
  specialColumnItemTouch:{
    backgroundColor: '#fff',
  },
  specialColumnItem: {
    flexDirection: 'row',
    padding: totalWidth*0.05,
    justifyContent: 'space-between',
    /*shadowOffset:{  
      width: 1,  
      height: 0.5,  
    },  
    shadowColor: '#989898',  
    shadowOpacity: 0.5,*/
    borderBottomWidth: 1/PixelRatio.get(),
    borderColor: '#f3f3f3',
  },
  specialColumnItemLeft: {
    flex: 4,
    flexDirection: 'row',
    paddingLeft: totalWidth*0.02,
  },
  specialColumnItemPS: {
    width: totalWidth*0.1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginRight: totalWidth*0.03,
  },
  specialColumnPeriod: {
    color: '#777777',
    fontSize: 12,
    textAlignVertical: 'top',
  },
  specialColumnSign: {
    fontSize: 8,
  },
  specialColumnCon: {
    flex: 1,
  },
  specialColumnConTitle: {
    color: '#383838',
    fontSize: 12,
  },
  specialColumnConInfo: {
    marginTop: totalWidth*0.03,
    color: '#7e7e7e',
    fontSize: 9,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialColumnItemRight: {
    flex: 1,
    alignItems: 'flex-end'
  },
  specialColumnItemRightTime: {
    position: 'absolute',
    right: 0,
    top: -totalWidth*0.04,
    lineHeight: Math.round(totalWidth*0.04),
    color: '#9e9e9e',
    fontSize: 8,
  },
  coverImg: {
    width: totalWidth*0.14,
    height: totalWidth*0.14,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 2,
  },
  bottom: {
    width: totalWidth,
    minHeight: totalWidth*0.133,
    position: 'absolute',
    bottom: 0,
    /*shadowOffset:{  
      width: 1,  
      height: 0.5,  
    },  
    shadowColor: '#989898',  
    shadowOpacity: 1,*/
  },
  bottomCon: {
    paddingHorizontal: totalWidth*0.034,
    paddingVertical: totalWidth*0.03,
    backgroundColor: '#ffffff',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bottomLeft: {
    flex: 1,
  },
  bottomLeftT: {
    fontSize: 12,
    color: '#383838'
  },
  bottomLeftM: {
    fontSize: 10,
    color: '#ff4546',
    marginTop: 3,
  },
  bottomRight: {
    width: totalWidth*0.253,
    height: totalWidth*0.08,
    backgroundColor: '#ff4747',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 2,
  },
  bottomRightT: {
    color: '#fff',
    fontSize: 14,
  },

});